package com.zhilingshenghuo.app.zhly

import android.content.*
import android.util.Log
import android.view.View
import com.zhilingshenghuo.app.zhly.entity.*
import com.zhilingshenghuo.app.zhly.view.BaseActivity
import com.zhilingshenghuo.app.zhly.view.widget.*
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.activity_home.*
import com.bumptech.glide.request.RequestOptions
import java.net.URI
import com.google.gson.Gson
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.ThreadMode

import org.greenrobot.eventbus.Subscribe
import java.util.*
import kotlin.system.exitProcess
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaPlayer
import com.zhilingshenghuo.app.zhly.socket.JWebSocketClient
import com.zhilingshenghuo.app.zhly.socket.event.*
import com.zhilingshenghuo.app.zhly.utils.*
import com.kc.openset.OSETRewardVideo
import com.kc.openset.OSETVideoListener
import org.java_websocket.handshake.ServerHandshake
import org.jetbrains.anko.toast
import kotlin.collections.ArrayList
import com.lzy.okgo.callback.StringCallback

import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.yanzhenjie.permission.runtime.Permission


class HomeActivity : BaseActivity() {

    private lateinit var minePop: MinePopwindow
    private lateinit var detailPop: DeatilPopwindow
    private lateinit var exchangePop: ExchangeCoinPopwindow
    private lateinit var gameRecordPop: GameRecordPopWindow
    private lateinit var rulePop: RulePopwindow
    private lateinit var shopExchangePop: ShopExchangePopWindow

    private var client: JWebSocketClient? = null
    private var TAG = "Socket"
    private lateinit var mGson: Gson
//    private var isGoLogin = false

    private var isExit: Boolean = false
    private val timer = Timer()
    private var isLoginEnd = false
    private var isLoginOut = false

    //超级场
    private lateinit var mSuperGoldRoom: GetRoomTypeResponse.ListBean.DataBean

    //高级场
    private lateinit var mSeniorGoldRoom: GetRoomTypeResponse.ListBean.DataBean

    //中级场
    private lateinit var mMiddleGoldRoom: GetRoomTypeResponse.ListBean.DataBean

    //初级场
    private lateinit var mElementaryGoldRoom: GetRoomTypeResponse.ListBean.DataBean

    //练习场
    private lateinit var mPracticeGoldRoom: GetRoomTypeResponse.ListBean.DataBean

    //未锁定金币列表
    private lateinit var mGoldList: ArrayList<GetScoreListResponse.ListBean.DataBean>

    //锁定金币列表
    private lateinit var mLockGoldList: ArrayList<GetScoreListResponse.ListBean.DataBean>

    //判断是否为房间内兑换
    private var isRoomExchange = false

    //头像
    private var mFace = ""

    //判断是否已经登录进房间内
    private var isLogin = false

    //点击的房间位置
    private var selectPos = 0

    private var isShow = false

    private var isPause = false

    private var isLoadingEnd = false

    //播放器
    private lateinit var mMediaPlayer: MediaPlayer

    private var isPlayer = false

    //丢蛋列表
    private lateinit var sendList: ArrayList<SendRecordResponse.ListBean.DataBean>

    //砸蛋列表
    private lateinit var robList: ArrayList<RobRecordResponse.ListBean.DataBean>

    private var canPlayer = ""

    //今日观看广告次数
    private var surplusNum = 0

    //每天可观看广告次数
    private var everydayNum = 0

    //广告播放器
    private lateinit var rewardVideo: OSETRewardVideo

    private val HEART_BEAT_RATE = (2 * 1000 //每隔10秒进行一次对长连接的心跳检测
            ).toLong()

    override fun onBackPressed() {
        //判断是否退出
        if (!isExit) {
            isExit = true
            toast("再按一次返回键退出")
            //通过TimerTask延时2秒发送  如果在2秒之内点击 则不走本次判断 直接执行else
            val timerTask = object : TimerTask() {
                override fun run() {
                    isExit = false
                }
            }
            //启动任务
            timer.schedule(timerTask, 2000)
        } else {
            //退出
            finish()
            timer.cancel()
            exitProcess(0)
            super.onBackPressed()
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_home
    }

    override fun onResume() {
        super.onResume()
        if (isLogin) {
            isLogin = false
        }
    }

    //APP返回前台
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: AppResumeEvent) {
        canPlayer = ShareUtil.getInstance().get(ShareUtil.BACKGROUND_OPEN)
        if (canPlayer == "1") {
//            initPlayer()
        }
    }

    //APP切换后台
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: AppStopEvent) {
        isLoginOut = false
        mMediaPlayer.stop()
        mMediaPlayer.release()

        mHandler.removeCallbacks(heartBeatRunnable)
        if (Utils.isLogin()) {
            //退出登录
            val loginOutEntity =
                LoginOutEntity("Logout")
            val json = mGson.toJson(loginOutEntity)
            client?.send(json)
            finish()
        }
    }

    //房间看广告成功
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: PlayerSuccessEvent) {
        val playerEntity =
            PlayerEntity("advertisement")
        val json = mGson.toJson(playerEntity)
        client?.send(json)
    }

    //房间丢蛋详情
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: SendDetailEntity) {
        val json = mGson.toJson(event)
        client?.send(json)
    }

    //房间内传回砸蛋
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: HitGoldEvent) {
        when (event.type) {
            //砸蛋
            "RedBags.Rob" -> {
                val hitGoldEntity =
                    HitGoldEntity("RedBags.Rob", event.order_id)
                val json = mGson.toJson(hitGoldEntity)
                client?.send(json)
            }
        }
    }

    //房间内传回获取砸蛋信息
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: GetGameRecordEvent) {
        if (event.isGet) {
            getRecord()
        }
    }

    //房间内传回丢蛋
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: SendGoldEvent) {
        val sendGoldEntity =
            SendGoldEntity("RedBags.Send", event.select, event.rule_id)
        val json = mGson.toJson(sendGoldEntity)
        client?.send(json)
    }

    //房间内兑换
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: ExchangeCoinEvent) {
        isRoomExchange = event.isRoom
        //兑换金币
        val entity =
            ExchangeCoinEntity(
                event.type,
                event.ad_value
            )
        val json = mGson.toJson(entity)
        client?.send(json)
    }

    //检查更新
    private fun checkVersion() {
        OkGo.get<String>("http://app4.zhilingshenghuo.com/egg/version")
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {
                    val body: String = response.body()
                    val checkVersionBean = mGson.fromJson(body, CheckVersionResponse::class.java)


//                GlideUtils.getInstances().loadNormalImg(getContext(),binding.topImg,"/" + configEntity.top_ad_image);
                    try {
                        val versionName: String = packageManager
                            .getPackageInfo(packageName, 0).versionName
                        if (Utils.compareVersion(
                                checkVersionBean.data.version,
                                versionName
                            ) === 1
                        ) {
                            Utils.showWarnDialog(checkVersionBean, this@HomeActivity)
                        }
                    } catch (e: PackageManager.NameNotFoundException) {
                        e.printStackTrace()
                    }

                }
            })
    }

    //退出房间
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: LogOutEvent) {
        if (event.isLogOut) {
            //兑换金币
            val entity =
                LogOutEntity("RedBags.Logout")
            val json = mGson.toJson(entity)
            client?.send(json)
        }
    }

    //房间内兑换
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: RoomGetUserInfoEvent) {
        //获取个人信息
        val userInfoEntity = UserInfoEntity("user_info")
        val mInfoJson = mGson.toJson(userInfoEntity)
        client?.send(mInfoJson)
    }

    //房间内记录
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: GetRecordEvent) {
        EventBus.getDefault().post(RoomRecordEvent(sendList, robList))
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: GetSocketEvent) {
        val socketJson = event.json
        //处理socket 响应数据auth_token
        val response: BaseResponse = mGson.fromJson(socketJson, BaseResponse::class.java)
        if (!response.isResult) {
            if (!response.desc.contains("请登录") && !response.desc.contains("您已经登录了") && !response.desc.contains(
                    "余额不足"
                )
            ) {
                toast(response.desc)
            }
            if (response.desc.contains("很遗憾")) {
                val getUserEntity =
                    GetUserEntity("RedBags.GetUserInfo")
                val json = mGson.toJson(getUserEntity)
                client?.send(json)
                toast(response.desc)
            }
            if (response.desc.contains("余额不足")) {
                EventBus.getDefault().post(NotBalanceEvent(surplusNum, everydayNum))
            }
            return
        }
        when (response.getType()) {
            "auth_token" -> {
                isLoginEnd = true
                val getTokenEntity: GetTokenEntity =
                    mGson.fromJson(socketJson, GetTokenEntity::class.java)
                ShareUtil.getInstance().save(ShareUtil.APP_TOKEN, getTokenEntity.getToken())
                ShareUtil.getInstance().save(ShareUtil.USERID, "" + getTokenEntity.getUserId())
                //授权后开启登录
                val sendEntity =
                    LoginEntity("Login", getTokenEntity.userId, getTokenEntity.getToken())
                val json = mGson.toJson(sendEntity)
                client?.send(json)
            }
            "Login" -> {
                val loginResponse: LoginResponse =
                    mGson.fromJson(socketJson, LoginResponse::class.java)
                ivIcon.loadCircularImage(loginResponse.face, 0, this)
                tvCoinNum.text = loginResponse.user_score + ""
                tvLockCoinNum.text = loginResponse.lock_score + ""
                tvPhone.text = loginResponse.username
                //登录成功后获取公告信息
                //获取平台公告信息
                val noticesEntity = GetNoticesEntity("Platform.GetCommonNotices")
                val mJson = mGson.toJson(noticesEntity)
                client?.send(mJson)
                //刷新页面
                refreshView()

                //登录成功获取房间列表
                val roomListEntity =
                    GetRoomTypeEntity(
                        "get_room_type_list",
                        1,
                        100
                    )
                val json = mGson.toJson(roomListEntity)
                client?.send(json)
            }
            "Logout" -> {
                isLoginEnd = false
                val response: BaseResponse = mGson.fromJson(socketJson, BaseResponse::class.java)
                //退出成功
                if (response.isResult && isLoginOut) {
                    ShareUtil.getInstance().save(ShareUtil.ACCESS_TOKEN, "")
                    ShareUtil.getInstance().save(ShareUtil.APP_TOKEN, "")
                    ShareUtil.getInstance().save(ShareUtil.PHONE, "")
                    tvCoinNum.text = ""
                    tvLockCoinNum.text = ""
                    tvPhone.text = "未登录"
                    ivIcon.setImageResource(R.drawable.icon_header)
                    ivBlur.visibility = View.GONE
                    minePop.disMiss()
                }
            }
            "exchange_score" -> {
                toast("兑换成功")
                //刷新界面
                if (isRoomExchange) {
                    //房间内获取个人详情
                    val getUserEntity =
                        GetUserEntity("RedBags.GetUserInfo")
                    val json = mGson.toJson(getUserEntity)
                    client?.send(json)
                    isRoomExchange = false
                }
                val response: ExchangeCoinResponse =
                    mGson.fromJson(socketJson, ExchangeCoinResponse::class.java)
                if (response.isResult) {
                    tvCoinNum.text = response.user_score.user_score + ""
                    tvLockCoinNum.text = response.user_score.lock_score + ""
                } else {
                    ToastUtil.showToast(response.desc)
                }
                exchangePop.dissMiss()

            }
            //平台公告
            "Platform.GetCommonNotices" -> {
                val noticesResponse = mGson.fromJson(socketJson, NoticesResponse::class.java)
                val info: ArrayList<String> = ArrayList()
                for (index in 0 until noticesResponse.list.size) {
                    info.add(noticesResponse.list[index].contents)
                }
                marqueeView.startWithList(info)
                // 在代码里设置自己的动画
                marqueeView.startWithList(info, R.anim.anim_bottom_in, R.anim.anim_top_out)
            }
            "get_room_type_list" -> {
                val response: GetRoomTypeResponse =
                    mGson.fromJson(socketJson, GetRoomTypeResponse::class.java)
                val mRoomList =
                    response.list.data as ArrayList<GetRoomTypeResponse.ListBean.DataBean>
                //处理所得list 获得几个房间类型的实体类
                for (index in 0 until mRoomList.size) {
                    when (mRoomList[index].code) {
                        "super-gold" -> {
                            mSuperGoldRoom = mRoomList[index]
                        }
                        "senior-gold" -> {
                            mSeniorGoldRoom = mRoomList[index]
                        }
                        "middle-gold" -> {
                            mMiddleGoldRoom = mRoomList[index]
                        }
                        "elementary-gold" -> {
                            mElementaryGoldRoom = mRoomList[index]
                        }
                        "practice-peas" -> {
                            mPracticeGoldRoom = mRoomList[index]
                        }
                    }
                }
                isLoadingEnd = true
            }
            "RedBags.Login" -> {
                val intent = Intent(this, HitGoldActivity::class.java)
                when (selectPos) {
                    1 -> {
                        intent.putExtra("title", mElementaryGoldRoom.title)
                        intent.putExtra("score_type", mElementaryGoldRoom.score_type)
                    }
                    2 -> {
                        intent.putExtra("title", mMiddleGoldRoom.title)
                        intent.putExtra("score_type", mMiddleGoldRoom.score_type)
                    }
                    3 -> {
                        intent.putExtra("title", mSeniorGoldRoom.title)
                        intent.putExtra("score_type", mSeniorGoldRoom.score_type)
                    }
                    4 -> {
                        intent.putExtra("title", mSuperGoldRoom.title)
                        intent.putExtra("score_type", mSuperGoldRoom.score_type)
                    }
                    5 -> {
                        intent.putExtra("title", mPracticeGoldRoom.title)
                        intent.putExtra("score_type", mPracticeGoldRoom.score_type)
                    }
                }
                isLogin = true
                intent.putExtra("json", event.json)
                startActivity(intent)

            }
            "RedBags.SendMsg" -> {
                //获取个人详情
                val getUserEntity =
                    GetUserEntity("RedBags.GetUserInfo")
                val json = mGson.toJson(getUserEntity)
                client?.send(json)
            }
            //房间内获取个人信息
            "RedBags.GetUserInfo" -> {
                //发送event通知房间内更新信息
                EventBus.getDefault().post(SendEggSuccessEvent(event.json, 1))
            }
            //丢蛋
            "RedBags.Send" -> {
                toast("丢蛋成功")
                //发送event通知房间内更新信息
                //获取个人详情
                val getUserEntity =
                    GetUserEntity("RedBags.GetUserInfo")
                val json = mGson.toJson(getUserEntity)
                client?.send(json)
//                EventBus.getDefault().post(SendEggSuccessEvent(event.json, 2))
            }
            //丢蛋结束推送
            "RedBags.SendEndMsg" -> {
                //发送event让房间内的id更新
                EventBus.getDefault().post(SendEndMsgEvent(socketJson))
                //获取个人详情
                val getUserEntity =
                    GetUserEntity("RedBags.GetUserInfo")
                val json = mGson.toJson(getUserEntity)
                client?.send(json)
            }
            //砸蛋推送
            "RedBags.RobMsg" -> {
                EventBus.getDefault().post(RobEggsSuccessEvent(socketJson, "RedBags.RobMsg"))
            }
            //砸蛋成功
            "RedBags.Rob" -> {
                EventBus.getDefault().post(RobEggsSuccessEvent(socketJson, "RedBags.Rob"))
            }
            //丢蛋列表
            "get_send_list" -> {
                //一部分本页面处理  一部分发送到房间内
                //页面处理
                sendList = ArrayList()
                val sendRecordResponse = mGson.fromJson(socketJson, SendRecordResponse::class.java)
                sendList =
                    sendRecordResponse.list.data as ArrayList<SendRecordResponse.ListBean.DataBean>
//                EventBus.getDefault().post(RoomRecordEvent(sendList, robList))
            }
            //砸蛋列表
            "get_rob_list" -> {
                robList = ArrayList()
                val robRecordResponse = mGson.fromJson(socketJson, RobRecordResponse::class.java)
                robList =
                    robRecordResponse.list.data as ArrayList<RobRecordResponse.ListBean.DataBean>
//                EventBus.getDefault().post(RoomRecordEvent(sendList, robList))
            }
            //个人信息
            "user_info" -> {
                EventBus.getDefault().post(UserInfoEvent(socketJson))
                val userInfoResponse: UserInfoResponse =
                    mGson.fromJson(socketJson, UserInfoResponse::class.java)
                mFace = userInfoResponse.face
                //设置今天可看广告次数
                surplusNum = userInfoResponse.advertisement.surplus_num
                everydayNum = userInfoResponse.advertisement.everyday_num
                tvGoWatch.text = "免费金币 (" + surplusNum + "/" + everydayNum + ")"
//                ivIcon.loadCircularImage(userInfoResponse.face, 0, this)
                tvCoinNum.text = userInfoResponse.user_score
                tvLockCoinNum.text = userInfoResponse.lock_score
                //加载兑换pop
                exchangePop = object : ExchangeCoinPopwindow(
                    this@HomeActivity,
                    userInfoResponse.user_score,
                    userInfoResponse.lock_score,
                    userInfoResponse.ad_balance
                ) {
                    override fun exchange(num: Int) {
                        //兑换金币
                        val entity =
                            ExchangeCoinEntity(
                                "exchange_score",
                                num.toFloat()
                            )
                        val json = mGson.toJson(entity)
                        client?.send(json)
                    }

                    override fun onDisMiss() {
                        ivBlur.visibility = View.GONE
                    }
                }
            }
            //账变明细
            "get_score_list" -> {
                val getScoreListResponse =
                    mGson.fromJson(socketJson, GetScoreListResponse::class.java)
                if (getScoreListResponse.list.data.size > 0) {
                    if (getScoreListResponse.list.data[0].lock_score.equals("0.00")) {
                        mGoldList =
                            getScoreListResponse.list.data as ArrayList<GetScoreListResponse.ListBean.DataBean>
                    } else {
                        mLockGoldList =
                            getScoreListResponse.list.data as ArrayList<GetScoreListResponse.ListBean.DataBean>
                    }
                }

            }
            //房间内消息推送
            "RedBags.EventMsg" -> {
                EventBus.getDefault().post(EventMsgEvent(socketJson))
            }
            "get_send_detail" -> {
                EventBus.getDefault().post(SendDetailEvent(socketJson))
            }
            //观看广告
            "advertisement" -> {
                val playerResponse = mGson.fromJson(socketJson, PlayerResponse::class.java)
                tvCoinNum.text = playerResponse.user_score + ""
                tvLockCoinNum.text = playerResponse.lock_score + ""
            }
        }
    }

    //刷新当前页面
    private fun refreshView() {
        mGoldList = ArrayList()
        mLockGoldList = ArrayList()
        sendList = ArrayList()
        robList = ArrayList()
        //获取个人信息
        val userInfoEntity = UserInfoEntity("user_info")
        val mInfoJson = mGson.toJson(userInfoEntity)
        client?.send(mInfoJson)

        //获取 丢蛋记录列表
        val sendRecordEntity =
            GetSendRecordEntity("get_send_list", 1, 10000)
        val jsonSend = mGson.toJson(sendRecordEntity)
        client?.send(jsonSend)

        //获取 砸蛋记录列表
        val hitRecordEntity =
            GetSendRecordEntity("get_rob_list", 1, 10000)
        val jsonHit = mGson.toJson(hitRecordEntity)
        client?.send(jsonHit)

        //获取 金币流水明细
        val getScoreListEntity =
            GetScoreListEntity("get_score_list", "gold", 1, 10000)
        val getScoreJson = mGson.toJson(getScoreListEntity)
        client?.send(getScoreJson)

        //获取 锁定金币流水明细
        val getLockScoreListEntity =
            GetScoreListEntity("get_score_list", "lock_gold", 1, 10000)
        val getLockScoreJson = mGson.toJson(getLockScoreListEntity)
        client?.send(getLockScoreJson)
    }

    private fun getRecord() {
        //获取 丢蛋记录列表
        val sendRecordEntity =
            GetSendRecordEntity("get_send_list", 1, 10000)
        val json = mGson.toJson(sendRecordEntity)
        client?.send(json)

        //获取 砸蛋记录列表
        val hitRecordEntity =
            GetSendRecordEntity("get_rob_list", 1, 10000)
        val jsonHit = mGson.toJson(hitRecordEntity)
        client?.send(jsonHit)
    }

    private fun checkPermissions() {
        PermissionUtils.applicationPermissions(
            this,
            object : PermissionUtils.PermissionListener {
                override fun onSuccess(context: Context) {
                    checkVersion()
                }

                override fun onFailed(context: Context) {
                    toast("权限申请失败，请手动给予权限")
                    finish()
                }
            },
            Permission.Group.STORAGE
        )
    }

    //传回是否背景音乐开关
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: OpenBackgroundEvent) {
        if (event.isOpen) {
            initPlayer()
            mMediaPlayer.start()
        } else {
            mMediaPlayer.stop()
            mMediaPlayer.release()
        }
    }

    private fun initPlayer() {
        mMediaPlayer = MediaPlayer()
        mMediaPlayer.setDataSource(Constants.BACKGROUND_MUSIC)
        mMediaPlayer.prepareAsync()
        canPlayer = ShareUtil.getInstance().get(ShareUtil.BACKGROUND_OPEN)
        mMediaPlayer.setOnPreparedListener {
            if (canPlayer == "1") {
                mMediaPlayer.start()
            }
        }

        mMediaPlayer.setOnCompletionListener {
            mMediaPlayer.start()
        }
    }

    override fun initView() {
        super.initView()
        if (!isPlayer) {
            initPlayer()
            isPlayer = true
        }

        checkPermissions()
        EventBus.getDefault().register(this)
        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE) //开启心跳检测
        mGson = Gson()
        val bitmap = BitmapUtils.getViewBitmap(this, R.layout.activity_home)
        Glide.with(this).load(bitmap)
            .apply(RequestOptions.bitmapTransform(BlurTransformation(this, 10, 3)))
            .into(ivBlur)
        getToken(intent)
        //初始化播放器
        rewardVideo = OSETRewardVideo()
        rewardVideo.setVerify(true) //想要校验onreward里面的key，必须要设置这个！
    }

    override fun onDestroy() {
        super.onDestroy()
        AlertUtils.dismiss()
        rewardVideo.destory() //释放资源
        EventBus.getDefault().unregister(this)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        getToken(intent)
    }

    private fun getToken(intent: Intent?) {
        if (intent != null) {
            if (intent.hasExtra("token")) {
//                isGoLogin = true
                //获取当前登录信息显示
                ShareUtil.getInstance().save(ShareUtil.ACCESS_TOKEN, intent.getStringExtra("token"))
                val phone = intent.getStringExtra("phone")
                ShareUtil.getInstance().save(ShareUtil.PHONE, phone)

            }
        }
    }

    override fun onClick() {
        ivRule.setOnClickListener {
            ivBlur.visibility = View.VISIBLE
            rulePop = object : RulePopwindow(this@HomeActivity) {
                override fun onDisMiss() {
                    ivBlur.visibility = View.GONE
                }
            }
            rulePop.show()
        }

        ivShopExchange.setOnClickListener {
            ivBlur.visibility = View.VISIBLE
            shopExchangePop = object : ShopExchangePopWindow(this@HomeActivity) {
                override fun onDisMiss() {
                    ivBlur.visibility = View.GONE
                }
            }
            shopExchangePop.show()
        }
        llInformation.setOnClickListener {
            showMinePop()
        }

        ivMine.setOnClickListener {
            showMinePop()
        }

        //练习场
        ivRoomPractice.setOnClickListener {
            if (Utils.isLogin()) {
                if (isLoadingEnd) {
                    if (mPracticeGoldRoom.id != 0) {
                        selectPos = 5
                        val loginRoomEntity =
                            LoginRoomEntity(
                                "RedBags.Login",
                                ShareUtil.getInstance().get(ShareUtil.USERID),
                                ShareUtil.getInstance().get(ShareUtil.APP_TOKEN),
                                "",
                                mPracticeGoldRoom.id.toString()
                            )
                        val json = mGson.toJson(loginRoomEntity)
                        client?.send(json)
                    } else {
                        ToastUtil.showToast("房间信息加载失败，无法进入房间")
                    }
                } else {
                    toast("请等待用户信息加载")
                }
            } else {
                ToastUtil.showToast("请先登录")
            }
        }

        //初级房
        ivRoomPrimary.setOnClickListener {
            if (Utils.isLogin()) {
                if (isLoadingEnd) {
                    if (mElementaryGoldRoom.id != 0) {
                        selectPos = 1
                        val loginRoomEntity =
                            LoginRoomEntity(
                                "RedBags.Login",
                                ShareUtil.getInstance().get(ShareUtil.USERID),
                                ShareUtil.getInstance().get(ShareUtil.APP_TOKEN),
                                "",
                                mElementaryGoldRoom.id.toString()
                            )
                        val json = mGson.toJson(loginRoomEntity)
                        client?.send(json)
                    } else {
                        ToastUtil.showToast("房间信息加载失败，无法进入房间")
                    }
                } else {
                    toast("请等待用户信息加载")
                }
            } else {
                ToastUtil.showToast("请先登录")
            }
        }
        //中级场
        ivRoomMiddle.setOnClickListener {
            if (Utils.isLogin()) {
                if (isLoadingEnd) {
                    if (mMiddleGoldRoom.id != 0) {
                        selectPos = 2
                        val loginRoomEntity =
                            LoginRoomEntity(
                                "RedBags.Login",
                                ShareUtil.getInstance().get(ShareUtil.USERID),
                                ShareUtil.getInstance().get(ShareUtil.APP_TOKEN),
                                "",
                                mMiddleGoldRoom.id.toString()
                            )
                        val json = mGson.toJson(loginRoomEntity)
                        client?.send(json)
                    } else {
                        ToastUtil.showToast("房间信息加载失败，无法进入房间")
                    }
                } else {
                    toast("请等待用户信息加载")
                }
            } else {
                ToastUtil.showToast("请先登录")
            }
        }
        //高级场
        ivRoomHigh.setOnClickListener {
            if (Utils.isLogin()) {
                if (isLoadingEnd) {
                    if (mSeniorGoldRoom.id != 0) {
                        selectPos = 3
                        val loginRoomEntity =
                            LoginRoomEntity(
                                "RedBags.Login",
                                ShareUtil.getInstance().get(ShareUtil.USERID),
                                ShareUtil.getInstance().get(ShareUtil.APP_TOKEN),
                                "",
                                mSeniorGoldRoom.id.toString()
                            )
                        val json = mGson.toJson(loginRoomEntity)
                        client?.send(json)
                    } else {
                        ToastUtil.showToast("房间信息加载失败，无法进入房间")
                    }
                } else {
                    toast("请等待用户信息加载")
                }
            } else {
                ToastUtil.showToast("请先登录")
            }
        }
        //超级场
        ivRoomSuper.setOnClickListener {
            if (Utils.isLogin()) {
                if (mSuperGoldRoom.id != 0) {
                    if (isLoadingEnd) {
                        selectPos = 4
                        val loginRoomEntity =
                            LoginRoomEntity(
                                "RedBags.Login",
                                ShareUtil.getInstance().get(ShareUtil.USERID),
                                ShareUtil.getInstance().get(ShareUtil.APP_TOKEN),
                                "",
                                mSuperGoldRoom.id.toString()
                            )
                        val json = mGson.toJson(loginRoomEntity)
                        client?.send(json)
                    } else {
                        toast("请等待用户信息加载")
                    }
                } else {
                    ToastUtil.showToast("房间信息加载失败，无法进入房间")
                }
            } else {
                ToastUtil.showToast("请先登录")
            }
        }
        tvExchangeCoin.setOnClickListener {
            if (Utils.isLogin()) {
                ivBlur.visibility = View.VISIBLE
                exchangePop.show()
            } else {
                toast("请先登录")
            }
        }
        //观看广告
        llGoWatch.setOnClickListener {
            //当日还有看广告次数
            if (Utils.isLogin()) {
                if (!isLoadingEnd) {
                    toast("请等待用户信息加载")
                    return@setOnClickListener
                }
                if (surplusNum < everydayNum) {
                    loadReward()
                } else {
                    toast("今日已经没有观看次数了")
                }
            } else {
                toast("请先登录")
            }
        }
    }

    private fun loadReward() {
        //激励视频的数组
        val id = arrayOf<String>(
            Constants.OPEN_SET_COIN_ID,
            Constants.OPEN_SET_COIN_ID_TWO,
            Constants.OPEN_SET_COIN_ID_THREE,
            Constants.OPEN_SET_COIN_ID_FOUR,
            Constants.OPEN_SET_COIN_ID_FIVE
        )
        val random = Random()
        val index = random.nextInt(id.size)
        rewardVideo.load(this, id[index], object : OSETVideoListener {
            override fun onLoad() {
                //加载广告成功回调
                rewardVideo.showRewardAd(this@HomeActivity)
            }

            override fun onVideoStart() {
                mMediaPlayer.stop()
                Log.e("RewardVideo", "onVideoStart---")
            }

            override fun onReward(key: String) {
                //奖励回调(可以进行奖励的发放)
                // 验证地址 http://open-set-api.shenshiads.com/reward/check/<key>（返回数据: {"code": 0}，code为0表示验证成
                //发送观看成功给后台
                val playerEntity =
                    PlayerEntity("advertisement")
                val json = mGson.toJson(playerEntity)
                client?.send(json)
            }

            override fun onShow() {
                Log.e("RewardVideo", "onShow---")
            }

            override fun onError(s: String, s1: String) {
//                Log.e("openseterror", "code:" + s + "----message:" + s1);
                T.showShort("广告加载失败，请稍后再试~")
            }

            override fun onItemError(s: String, s1: String) {}
            override fun onClick() {
                Log.e("RewardVideo", "onClick---")
            }

            override fun onClose(key: String) {
                //关闭回调
                initPlayer()
                mMediaPlayer.start()
                Log.e("RewardVideo", "onClose---key:$key")
//                rewardVideo.destory() //释放资源
            }

            override fun onVideoEnd(key: String) {
                //视频播放完成回调
                Log.e("RewardVideo", "onVideoEnd---key:$key")
            }
        })
    }

    private fun showMinePop() {
        isShow = false
        ivBlur.visibility = View.VISIBLE
        minePop = object : MinePopwindow(this@HomeActivity, mFace) {
            override fun loginOut() {
                if (Utils.isLogin()) {
                    isLoginOut = true
                    //退出登录
                    val loginOutEntity =
                        LoginOutEntity("Logout")
                    val json = mGson.toJson(loginOutEntity)
                    client?.send(json)
                }
            }

            override fun changeUser() {

//                    if(!isAvilible(getContext(), "com.zhilingshenghuo.app"))
//                    {
//                        ToastUtil.showToast("请安装智领生活APP！");
//                        return;
//                    }
                val intent = Intent()
                intent.action = Intent.ACTION_MAIN
                intent.addCategory(Intent.CATEGORY_LAUNCHER)
                intent.flags = (Intent.FLAG_ACTIVITY_NEW_TASK
                        or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
                intent.component =
                    ComponentName("com.example.csc", "com.app.csc.activity.SplashActivity")

                intent.putExtra("name", "goldEggs")
                intent.putExtra("type", "NEW_GAME")
                intent.putExtra("code", "6c0271860fad358708fb72f7f89e744e")
                intent.putExtra(
                    "apptag",
                    "com.zhilingshenghuo.app.zhly"
                ) //com.example.csc   com.cscex.app

                startActivityForResult(intent, 100)
                minePop.disMiss()
                finish()
            }

            override fun getDetail() {
                isShow = true
                minePop.disMiss()
                //账户明细
                initDetailPop()
                detailPop.show()
            }

            override fun gameRecord() {
                isShow = true
                minePop.disMiss()
                //游戏记录
                initRecordPop()
                gameRecordPop.show()
            }

            override fun exchangeCoin() {
                isShow = true
                //金币兑换
                minePop.disMiss()
                exchangePop.show()
            }

            override fun callCustomer() {

            }

            override fun onDisMiss() {
                if (!isShow) {
                    ivBlur.visibility = View.GONE
                }

            }
        }
        minePop.show()
    }

    private fun initDetailPop() {
        detailPop = object : DeatilPopwindow(this@HomeActivity, mGoldList, mLockGoldList) {
            override fun onDisMiss() {
                ivBlur.visibility = View.GONE
            }
        }
    }

    private fun initRecordPop() {
        gameRecordPop = object : GameRecordPopWindow(this@HomeActivity, sendList, robList) {
            override fun onDisMiss() {
                ivBlur.visibility = View.GONE
            }
        }
    }

    /**
     * 初始化websocket连接
     */
    private fun initSocketClient() {
//        val uri = URI.create("ws://prezjd.xiaopankeji.com:10886") //预发测试环境
//      val uri = URI.create("ws://106.14.226.205:8886") //测试使用
        val uri = URI.create("ws://zjdapi.xiaopankeji.com:8886") //正式使用
        client = object : JWebSocketClient(uri) {
            override fun onMessage(message: String) {
                Log.e("JWebSocketClientService", "收到的消息：$message")
                //逻辑处理判断哪个socket返回数据再eventBus发送数据到响应位置
                EventBus.getDefault().post(GetSocketEvent(message))
            }

            override fun onOpen(handshakedata: ServerHandshake) {
                super.onOpen(handshakedata)
                EventBus.getDefault().post(SocketOpenEvent(true))
                Log.e("JWebSocketClientService", "websocket连接成功")
            }
        }
        connect()
    }

    /**
     * 连接websocket
     */
    private fun connect() {
        object : Thread() {
            override fun run() {
                try {
                    //connectBlocking多出一个等待操作，会先连接再发送，否则未连接发送会报错
                    client!!.connectBlocking()
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }.start()
    }

    //    -------------------------------------websocket心跳检测------------------------------------------------
    private val mHandler = android.os.Handler()
    private val heartBeatRunnable: Runnable = object : Runnable {
        override fun run() {
            if (client != null) {
                if (client!!.isClosed) {
                    reconnectWs()
                } else {
                    //业务逻辑 这里如果服务端需要心跳包为了防止断开 需要不断发送消息给服务端
                    val heartBean = SocketHeartBean("empty")
                    val json: String = mGson.toJson(heartBean)
                    client!!.send(json)
                    //判断是否已经登录
                    if (Utils.isLogin()) {
                        //发送数据请求token
                        if (!isLoginEnd) {
                            val entity =
                                AuthTokenEntity(
                                    "auth_token",
                                    ShareUtil.getInstance().get(ShareUtil.ACCESS_TOKEN)
                                )
                            val json = mGson.toJson(entity)
                            client?.send(json)
                        }
                    } else {
                        tvPhone.text = "未登录"
//            ivIcon.setImageResource(R.drawable.icon_header)
                    }
                    refreshView()
                }
            } else {
                //如果client已为空，重新初始化连接
                client = null
                initSocketClient()
            }
            //每隔一定的时间，对长连接进行一次心跳检测
            mHandler.postDelayed(this, HEART_BEAT_RATE)
            Log.e("JWebSocketClientService", "心跳包检测websocket连接状态")
        }
    }

    /**
     * 开启重连
     */
    private fun reconnectWs() {
        mHandler.removeCallbacks(heartBeatRunnable)
        object : Thread() {
            override fun run() {
                try {
                    Log.e("JWebSocketClientService", "开启重连")
                    client!!.reconnectBlocking()
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }.start()
    }

}